<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/24 14:00:35 $)
// $RCSfile: staff_users.php,v $ : $Revision: 1.19 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

if ($_SWIFT["staff"]["cu_entab"] == "0")
{
	echo '<font face="Verdana, Arial, Helvetica" size="2" color="red"><b>'.$_SWIFT["language"]["nopermission"].'</b></font>';
	exit;
}

require_once ("./includes/functions_html.php");
require_once ("./includes/functions_users.php");
require_once ("./includes/functions_customfields.php");
$template->loadLanguageSection("staff_users");
$template->loadLanguageSection("staff_userpermissions");

$interface->assignQuickLink($_SWIFT["language"]["manageusers"], "index.php?_m=core&_a=manageusers", "icon_users.gif");
$interface->assignQuickLink($_SWIFT["language"]["managegroups"], "index.php?_m=core&_a=manageusergroups", "icon_usergroupregistered.gif");
$interface->assignQuickLink($_SWIFT["language"]["insertuser"], "index.php?_m=core&_a=insertuser", "icon_insertuser.gif");
$interface->assignQuickLink($_SWIFT["language"]["insertgroup"], "index.php?_m=core&_a=insertusergroup", "icon_insertusergroup.gif");
$interface->assignQuickLink($_SWIFT["language"]["massmail"], "index.php?_m=core&_a=usermassmail", "icon_massmail.gif");

/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/

// ======= USERS =======

/**
* Callback for user list
*/
function _usersFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["useremails.email"] =  '<img src="'. $_SWIFT["themepath"] .iif($record["enabled"]=="1", 'icon_user.gif', 'icon_usernotvalidated.gif').'" align="absmiddle" border="0" />&nbsp;<a href="index.php?_m=core&_a=edituser&userid='. $record["userid"] .'" title="'. $_SWIFT["language"]["edit"] .'">'.htmlspecialchars($record["email"]).'</a>';
	$record["users.fullname"] = '<a href="index.php?_m=core&_a=edituser&userid='. $record["userid"] .'" title="'. $_SWIFT["language"]["edit"] .'">'.htmlspecialchars($record["fullname"]).'</a>';

	
	if ($record["grouptype"] == USERGROUP_GUEST)
	{
		$record["usergroups.title"] = '<img src="'. $_SWIFT["themepath"] .'icon_usergroupguest.gif" border="0" /> '.htmlspecialchars($record["title"]);
	} else if ($record["grouptype"] == USERGROUP_REGISTERED) {
		$record["usergroups.title"] = '<img src="'. $_SWIFT["themepath"] .'icon_usergroupregistered.gif" border="0" /> '.htmlspecialchars($record["title"]);
	}

	$record["users.dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["dateline"]);
	if (!empty($record["users.lastvisit"]))
	{
		$record["users.lastvisit"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["lastvisit"]);
	}

	$record["users.userid"] = intval($record["userid"]);

	$record["options"] = '<a href="index.php?_m=core&_a=edituser&userid='. $record["userid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["userdelconfirmmsg"] .'\', \'index.php?_m=core&_a=manageusers&do=delete&userid='. $record["userid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';

	return $record;
}

/**
* Deletes the given users
*/
function _maDeleteUsers()
{
	global $dbCore, $_SWIFT;

	if (is_array($_POST["itemid"]))
	{
		deleteUsers($_POST["itemid"]);
	}
}

/**
* Validation Status
*/
function _maValidated()
{
	global $dbCore, $_SWIFT;

	if (is_array($_POST["itemid"]))
	{
		changeUserValidationStatus($_POST["itemid"], 1);
	}
}

/**
* Validation Status
*/
function _maValidationPending()
{
	global $dbCore, $_SWIFT;

	if (is_array($_POST["itemid"]))
	{
		changeUserValidationStatus($_POST["itemid"], 0);
	}
}

// ======= USER GROUPS =======

/**
* Callback for user group list
*/
function _userGroupFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	if ($record["grouptype"] == USERGROUP_GUEST)
	{
		$record["grouptype"] = '<img src="'. $_SWIFT["themepath"] .'icon_usergroupguest.gif" border="0" /> '.$_SWIFT["language"]["ugroupguest"];
	} else if ($record["grouptype"] == USERGROUP_REGISTERED) {
		$record["grouptype"] = '<img src="'. $_SWIFT["themepath"] .'icon_usergroupregistered.gif" border="0" /> '.$_SWIFT["language"]["ugroupregistered"];
	}

	$record["title"] = '<a href="index.php?_m=core&_a=editusergroup&usergroupid='. $record["usergroupid"] .'">'. htmlspecialchars($record["title"]) .'</a>';

	$record["options"] = '<a href="index.php?_m=core&_a=editusergroup&usergroupid='. $record["usergroupid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["ugroupdelconfirmmsg"] .'\', \'index.php?_m=core&_a=manageusergroups&do=delete&usergroupid='. $record["usergroupid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';

	return $record;
}

/**
* Deletes the given user groups
*/
function _maDeleteUserGroups()
{
	global $dbCore, $_SWIFT, $errormessage;

	if (is_array($_POST["itemid"]))
	{
		$delresult = deleteUserGroups($_POST["itemid"]);
		if ($delresult == -1)
		{
			$errormessage = $_SWIFT["language"]["cantdelmastergroup"];
		} else {
			$infomessage = $_SWIFT["language"]["ugroupdelconfirm"];
		}
	}	
}

// ======= USER EMAILS =======

/**
* Callback for user emails list
*/
function _userEmailFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["email"] = '<a href="index.php?_m=core&_a=edituseremail&useremailid='. $record["useremailid"] .'" title="'. $_SWIFT["language"]["edit"] .'">'.htmlspecialchars($record["email"]).'</a>';

	$record["options"] = '<a href="index.php?_m=core&_a=edituseremail&useremailid='. $record["useremailid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["uemaildelconfirmsg"] .'\', \'index.php?_m=core&_a=edituser&userid='. $_REQUEST["userid"] .'&do=deleteuseremail&useremailid='. $record["useremailid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';

	return $record;
}

/**
* Deletes the given user email
*/
function _maDeleteUserEmails()
{
	global $dbCore, $_SWIFT, $griderrormessage, $gridinfomessage;

	if (is_array($_POST["itemid"]))
	{
		$delresult = deleteUserEmails($_REQUEST["userid"], $_POST["itemid"]);

		if ($delresult == -1)
		{
			$griderrormessage = $_SWIFT["language"]["cantdelprimaryemail"];
		} else {
			$gridinfomessage = $_SWIFT["language"]["useremaildelconfirm"];
		}
	}	
}














/**
* ###############################################
* MANAGE USERS
* ###############################################
*/
if ($eventaction == "manageusers")
{
	if ($_GET["do"] == "delete" && !empty($_GET["userid"]))
	{
		$infomessage = $_SWIFT["language"]["userdelconfirm"];

		deleteUsers(array($_GET["userid"]));
	}

	if (trim($_GET["insertuser"]) != "")
	{
		$infomessage = sprintf($_SWIFT["language"]["userinsertconfirm"], $_GET["insertuser"]);
	} else if (trim($_GET["updateuser"]) != "") {
		$infomessage = sprintf($_SWIFT["language"]["userupdateconfirm"], $_GET["updateuser"]);
	}

	$options["recordsperpage"] = "12";
	$options["sortby"] = "users.dateline";
	$options["sortorder"] = "desc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteUsers";
	$options["massaction"][1]["title"] = $_SWIFT["language"]["markasvalidated"];
	$options["massaction"][1]["callback"] = "_maValidated";
	$options["massaction"][2]["title"] = $_SWIFT["language"]["markasvalidationpending"];
	$options["massaction"][2]["callback"] = "_maValidationPending";

	$options["idname"] = "userid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["usrfullnameandemail"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'users` AS users LEFT JOIN `'. TABLE_PREFIX .'usergroups` AS usergroups ON (users.usergroupid = usergroups.usergroupid) LEFT JOIN `'. TABLE_PREFIX .'useremails` AS useremails ON (users.userid = useremails.userid) WHERE users.fullname LIKE \'%$_searchstr%\' OR useremails.email LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["advancedsearch"][1]["title"] = $_SWIFT["language"]["usrfullname"];
	$options["advancedsearch"][1]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'users` AS users LEFT JOIN `'. TABLE_PREFIX .'usergroups` AS usergroups ON (users.usergroupid = usergroups.usergroupid) LEFT JOIN `'. TABLE_PREFIX .'useremails` AS useremails ON (users.userid = useremails.userid) WHERE users.fullname LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["advancedsearch"][2]["title"] = $_SWIFT["language"]["usremail"];
	$options["advancedsearch"][2]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'users` AS users LEFT JOIN `'. TABLE_PREFIX .'usergroups` AS usergroups ON (users.usergroupid = usergroups.usergroupid) LEFT JOIN `'. TABLE_PREFIX .'useremails` AS useremails ON (users.userid = useremails.userid) WHERE useremails.email LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_usersFields";

	$fields[0]["name"] = "useremails.email";
	$fields[0]["title"] = $_SWIFT["language"]["usremail"];
	$fields[0]["width"] = "";
	$fields[0]["custom"] = true;

	$fields[1]["name"] = "users.fullname";
	$fields[1]["title"] = $_SWIFT["language"]["usrfullname"];
	$fields[1]["width"] = "200";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "users.userid";
	$fields[2]["title"] = $_SWIFT["language"]["usruserid"];
	$fields[2]["width"] = "80";
	$fields[2]["align"] = "center";

	$fields[3]["name"] = "usergroups.title";
	$fields[3]["title"] = $_SWIFT["language"]["usrgrouptitle"];
	$fields[3]["width"] = "150";
	$fields[3]["align"] = "center";

	$fields[4]["name"] = "users.dateline";
	$fields[4]["title"] = $_SWIFT["language"]["usrdate"];
	$fields[4]["width"] = "150";
	$fields[4]["align"] = "center";

/*	$fields[4]["type"] = "custom";
	$fields[4]["name"] = "options";
	$fields[4]["title"] = $_SWIFT["language"]["options"];
	$fields[4]["width"] = "160";
	$fields[4]["align"] = "center";*/

	$grid = new Grid();

	$interface->staffHeader($_SWIFT["language"]["users"]." &gt; ".$_SWIFT["language"]["manage"], 9);

	$interface->staffNavBar('<a href="index.php?_m=core&_a=manageusers" title="'.$_SWIFT["language"]["manageusers"].'">'.$_SWIFT["language"]["manageusers"].'</a>', "", 9);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	$_selectquery = 'SELECT * FROM `'. TABLE_PREFIX .'users` AS users LEFT JOIN `'. TABLE_PREFIX .'usergroups` AS usergroups ON (users.usergroupid = usergroups.usergroupid) LEFT JOIN `'. TABLE_PREFIX .'useremails` AS useremails ON (users.userid = useremails.userid) $_sortjoin;';
	$_countquery = 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'users` AS users LEFT JOIN `'. TABLE_PREFIX .'useremails` AS useremails ON (users.userid = useremails.userid);';
	$_searchquery = 'SELECT * FROM `'. TABLE_PREFIX .'users` AS users LEFT JOIN `'. TABLE_PREFIX .'usergroups` AS usergroups ON (users.usergroupid = usergroups.usergroupid) LEFT JOIN `'. TABLE_PREFIX .'useremails` AS useremails ON (users.userid = useremails.userid) WHERE users.fullname LIKE \'%$_searchstr%\' OR useremails.email LIKE \'%$_searchstr%\' $_sortjoin;';
	
	$grid->start("users", $_SWIFT["language"]["userlist"], $_selectquery, $_countquery, $_searchquery, $fields, $options);
	$grid->display("users");

	echo '<BR /><span class="smalltext">'. $_SWIFT["language"]["legend"] .' <img src="'. $_SWIFT["themepath"] .'icon_user.gif" border="0" /> '. $_SWIFT["language"]["validated"].'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_usernotvalidated.gif" border="0" /> '. $_SWIFT["language"]["validationpending"].'</span>';

	$interface->staffFooter();





/**
* ###############################################
* MANAGE USER GROUPS
* ###############################################
*/
} else if ($eventaction == "manageusergroups") {
	if ($_GET["do"] == "delete" && !empty($_GET["usergroupid"]) && $_SWIFT["isdemo"] != true)
	{
		$delresult = deleteUserGroups(array($_GET["usergroupid"]));
		if ($delresult == -1)
		{
			$errormessage = $_SWIFT["language"]["cantdelmastergroup"];
		} else {
			$infomessage = $_SWIFT["language"]["ugroupdelconfirm"];
		}
	}

	if (trim($_GET["insertgroup"]) != "")
	{
		$infomessage = sprintf($_SWIFT["language"]["ugroupinsertconfirm"], htmlspecialchars($_GET["insertgroup"]));
	} else if (trim($_GET["updategroup"]) != "") {
		$infomessage = sprintf($_SWIFT["language"]["ugroupupdateconfirm"], htmlspecialchars($_GET["updategroup"]));
	}

	$options["recordsperpage"] = "8";
	$options["sortby"] = "title";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteUserGroups";

	$options["idname"] = "usergroupid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["ugrouptitle"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'users` AS users LEFT JOIN `'. TABLE_PREFIX .'usergroups` AS usergroups ON (users.usergroupid = usergroups.usergroupid) LEFT JOIN `'. TABLE_PREFIX .'useremails` AS useremails ON (users.userid = useremails.userid) WHERE users.fullname LIKE \'%$_searchstr%\' OR useremails.email LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_userGroupFields";

	$fields[0]["name"] = "title";
	$fields[0]["title"] = $_SWIFT["language"]["ugrouptitle"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "grouptype";
	$fields[1]["title"] = $_SWIFT["language"]["ugrouptype"];
	$fields[1]["width"] = "200";
	$fields[1]["align"] = "center";

/*	$fields[2]["type"] = "custom";
	$fields[2]["name"] = "options";
	$fields[2]["title"] = $_SWIFT["language"]["options"];
	$fields[2]["width"] = "160";
	$fields[2]["align"] = "center";*/

	$grid = new Grid();

	$interface->staffHeader($_SWIFT["language"]["usergroups"]." &gt; ".$_SWIFT["language"]["manage"], 9);

	$interface->staffNavBar('<a href="index.php?_m=core&_a=manageusers" title="'.$_SWIFT["language"]["users"].'">'.$_SWIFT["language"]["users"].'</a> &raquo; '.'<a href="index.php?_m=core&_a=manageusergroups" title="'.$_SWIFT["language"]["usergroups"].'">'.$_SWIFT["language"]["usergroups"].'</a>', "", 9);


	$_selectquery = 'SELECT * FROM `'. TABLE_PREFIX .'usergroups` $_sortjoin;';
	$_countquery = 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'usergroups`;';
	$_searchquery = 'SELECT * FROM `'. TABLE_PREFIX .'usergroups` WHERE title LIKE \'%$_searchstr%\' $_sortjoin;';
	
	$grid->start("usergroups", $_SWIFT["language"]["usergrouplist"], $_selectquery, $_countquery, $_searchquery, $fields, $options);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	$grid->display("usergroups");

	echo '<BR /><span class="smalltext">'. $_SWIFT["language"]["legend"] .' <img src="'. $_SWIFT["themepath"] .'icon_usergroupguest.gif" border="0" /> '. $_SWIFT["language"]["ugroupguest"].'&nbsp;&nbsp;&nbsp; <img src="'. $_SWIFT["themepath"] .'icon_usergroupregistered.gif" border="0" /> '. $_SWIFT["language"]["ugroupregistered"].'</span>';

	$interface->staffFooter();






/**
* ###############################################
* MASS MAIL
* ###############################################
*/
} else if ($eventaction == "usermassmail") {
	if ($_POST["step"] == "1")
	{
		if (trim($_POST["subject"]) == "" || trim($_POST["contents"]) == "" || trim($_POST["fromname"]) == "" || trim($_POST["fromemail"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_SWIFT["isdemo"] == true) {
			$errormessage = $_SWIFT["language"]["demomode"];
		} else if (!_is_array($_POST["usergroupidlist"])) {
			$errormessage = $_SWIFT["language"]["selectonegroup"];
		} else if (!isValidEmail($_POST["fromemail"])) {
			$errormessage = $_SWIFT["language"]["specifyvalidemail"];
		} else {
			$mailcount = sendUserMassMail($_POST["usergroupidlist"], $_POST["subject"], $_POST["contents"], $_POST["fromname"], $_POST["fromemail"]);

			printRedirect(sprintf($_SWIFT["language"]["sentmailconfirm"], $mailcount), "index.php?_m=core&_a=usermassmail&mailcount=".intval($mailcount));
			exit;
		}
	}
	//Mahesh Slaria: Fixed the Mass mail HTML tags problem.
	if ($_SWIFT["settings"]["cpu_enablehtmlmails"] == 1)
	{
		$template->assign("htmlarea", true);
		$template->assign("htmlareanotable", true);
	}

	if (trim($_GET["mailcount"]) != "")
	{
		$infomessage = sprintf($_SWIFT["language"]["sentmailconfirm"], $_GET["mailcount"]);
	}

	$interface->staffHeader($_SWIFT["language"]["users"]." &gt; ".$_SWIFT["language"]["massmail"], 9);

	$interface->staffNavBar('<a href="index.php?_m=core&_a=manageusers" title="'.$_SWIFT["language"]["users"].'">'.$_SWIFT["language"]["users"].'</a> &raquo; '.'<a href="index.php?_m=core&_a=usermassmail" title="'.$_SWIFT["language"]["massmail"].'">'.$_SWIFT["language"]["massmail"].'</a>', "", 9);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	printFormStart("massmailform");

	printMainTableHeader($_SWIFT["language"]["massmail"]);
	printTextRow("subject", $_SWIFT["language"]["mmsubject"], $_SWIFT["language"]["desc_mmsubject"], "text", $_POST["subject"], "50");
	printTextRow("fromname", $_SWIFT["language"]["mmfromname"], $_SWIFT["language"]["desc_mmfromname"], "text", $_SWIFT["staff"]["fullname"], "35");
	printTextRow("fromemail", $_SWIFT["language"]["mmfromemail"], $_SWIFT["language"]["desc_mmfromemail"], "text", $_SWIFT["settings"]["general_returnemail"], "35");
	
	$options = array();
	$cnt = 0;
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."usergroups` ORDER BY `title` ASC;");
	while ($dbCore->nextRecord())
	{
		$options[$cnt]["title"] = $dbCore->Record["title"];
		$options[$cnt]["value"] = $dbCore->Record["usergroupid"];
		$options[$cnt]["checked"] = true;
		$cnt++;
	}
	printCheckboxListRow("usergroupidlist", $_SWIFT["language"]["mmusergroups"], $_SWIFT["language"]["desc_mmusergroups"], $options);

	if ($_SWIFT["settings"]["cpu_enablehtmlmails"] == 1)
	{
		printhtmlAreaRow("contents", $_SWIFT["language"]["mmcontents"], $_POST["contents"]);
	} else {
		printDescRow($_SWIFT["language"]["mmcontents"]);
		$data = array();
		$data[0]["value"] = '<textarea style="WIDTH:100%;" name="contents" id="contents" class="swifttextarea" cols="100" rows="15">'. htmlspecialchars($_POST["contents"]) .'</textarea>'.SWIFT_CRLF;
		$data[0]["align"] = "left";
		$data[0]["colspan"] = "2";
		printDataRow($data);
	}
	
	printSubmitRow($_SWIFT["language"]["mmsend"]);

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", "usermassmail");
	addHiddenField("step", "1");
	printFormEnd();

	$template->assign("backurl", "index.php?_m=core&_a=manageusers");
	$interface->adminFooter();









/**
* ###############################################
* INSERT NEW USER GROUP
* ###############################################
*/
} else if ($eventaction == "insertusergroup") {
	if ($_POST["step"] == "1")
	{
		if (trim($_POST["title"]) == "" || !checkCustomFieldContent(CUSTOMFIELD_USERGROUP))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_SWIFT["isdemo"] == true) {
			$errormessage = $_SWIFT["language"]["demomode"];
		} else {
			$usergroupid = insertUserGroup($_POST["title"], iif($_POST["grouptype"]==USERGROUP_REGISTERED, USERGROUP_REGISTERED, USERGROUP_GUEST), $_POST["perm"]);
			if ($usergroupid)
			{
				updateCustomFields(CUSTOMFIELD_USERGROUP, $usergroupid);
			}
			if (!empty($_POST["slaplanid"]))
			{
				updateUserGroupSLAPlan($usergroupid, $_POST["slaplanid"]);
			}

			printRedirect(sprintf($_SWIFT["language"]["ugroupinsertconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=core&_a=manageusergroups&insertgroup=".urlencode($_POST["title"]));
			exit;
		}
	}

	$interface->staffHeader($_SWIFT["language"]["users"]." &gt; ".$_SWIFT["language"]["insertgroup"], 9);

	$interface->staffNavBar('<a href="index.php?_m=core&_a=manageusergroups" title="'.$_SWIFT["language"]["usergroups"].'">'.$_SWIFT["language"]["usergroups"].'</a> &raquo; '.'<a href="index.php?_m=core&_a=insertusergroup" title="'.$_SWIFT["language"]["insertgroup"].'">'.$_SWIFT["language"]["insertgroup"].'</a>', "", 9);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderUserGroupForm(INSERT);

	$template->assign("backurl", "index.php?_m=core&_a=manageusergroups");
	$interface->staffFooter();






/**
* ###############################################
* EDIT USER GROUP
* ###############################################
*/
} else if ($eventaction == "editusergroup") {
	$_usergroup = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."usergroups` WHERE `usergroupid` = '". intval($_REQUEST["usergroupid"]) ."';");
	if (empty($_usergroup["usergroupid"]))
	{
		trigger_error($_SWIFT["language"]["invalidusergroup"], E_USER_ERROR);
	}

	// Ok.. now fetch the permissions.
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."usergroupsettings` WHERE `usergroupid` = '". intval($_usergroup["usergroupid"]) ."';");
	while ($dbCore->nextRecord())
	{
		$permissions[$dbCore->Record["name"]] = $dbCore->Record["value"];
	}

	// ======= UPDATE PROCESSING =======
	if ($_POST["step"] == "1")
	{
		if (trim($_POST["title"]) == "" || !checkCustomFieldContent(CUSTOMFIELD_USERGROUP))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_SWIFT["isdemo"] == true) {
			$errormessage = $_SWIFT["language"]["demomode"];
		} else {
			updateUserGroup($_usergroup["usergroupid"], $_POST["title"], iif($_POST["grouptype"]==USERGROUP_REGISTERED, USERGROUP_REGISTERED, USERGROUP_GUEST), $_POST["perm"]);
			updateCustomFields(CUSTOMFIELD_USERGROUP, $_usergroup["usergroupid"]);

			updateUserGroupSLAPlan($_usergroup["usergroupid"], $_POST["slaplanid"]);

			printRedirect(sprintf($_SWIFT["language"]["ugroupupdateconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=core&_a=manageusergroups&updategroup=".urlencode($_POST["title"]));
			exit;
		}
	}

	$template->assign("itemoptiontitle", $_SWIFT["language"]["groupoptions"]);
	$template->assign("usergroupid", $_usergroup["usergroupid"]);
	if ($module->isRegistered(MODULE_TICKETS))
	{
		$template->assign("isedituser", true);
		$template->assign("cpdepartments", $_SWIFT["departmentcache"]);
		$template->assign("cpdepcount", count($_SWIFT["departmentcache"]));
		$template->assign("cpstatus", $_SWIFT["statuscache"]);
		$template->assign("nousermenu", true);
		$template->assign("cpstatuscount", count($_SWIFT["statuscache"]));
		$interface->assignItemOption($_SWIFT["language"]["tusearchticket"], "", "icon_searchlookup.gif", "tusearchticket", '');
//		$interface->assignItemOption($_SWIFT["language"]["tusearchticket"], "index.php?_m=tickets&_a=search&usergroupid=".intval($_usergroup["usergroupid"]), "icon_searchlookup.gif", "", '');
	}
	$interface->assignItemOption($_SWIFT["language"]["deletegroup"], "", "icon_delete.gif", "", 'doConfirm(\''. $_SWIFT["language"]["ugroupdelconfirmmsg"] .'\', \'index.php?_m=core&_a=manageusergroups&do=delete&usergroupid='. $_usergroup["usergroupid"] .'\')');

	$_POST = array_merge($_POST, $_usergroup);

	$interface->staffHeader($_SWIFT["language"]["usergroups"]." &gt; ".$_SWIFT["language"]["editgroup"], 9);

	$interface->staffNavBar('<a href="index.php?_m=core&_a=manageusergroups" title="'.$_SWIFT["language"]["usergroups"].'">'.$_SWIFT["language"]["usergroups"].'</a> &raquo; '.'<a href="index.php?_m=core&_a=editusergroup&usergroupid='. $_usergroup["usergroupid"] .'" title="'.$_SWIFT["language"]["editgroup"].'">'.$_SWIFT["language"]["editgroup"].'</a>', "", 9);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderUserGroupForm(EDIT);

	$template->assign("backurl", "index.php?_m=core&_a=manageusergroups");
	$interface->staffFooter();








/**
* ###############################################
* INSERT NEW USER
* ###############################################
*/
} else if ($eventaction == "insertuser") {
	if ($_POST["step"] == "1")
	{
		if (trim($_POST["fullname"]) == "" || trim($_POST["email"]) == "" || trim($_POST["password"]) == "" || trim($_POST["passwordconfirm"]) == "" || !checkCustomFieldContent(CUSTOMFIELD_USER))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_POST["password"] != $_POST["passwordconfirm"]) {
			$errormessage = $_SWIFT["language"]["passworddontmatch"];
		} else if (!isValidEmail($_POST["email"])) {
			$errormessage = $_SWIFT["language"]["invalidemail"];
		} else {
			$userid = insertUser(true, $_POST["email"], $_POST["password"], $_POST["usergroupid"], LOGINAPI_DEFAULT, 0, $_POST["fullname"], 1, 0, false, 1, false, false, iif($_POST["ismanager"]=="1", true, false));
			if (!$userid)
			{
				$errormessage = $_SWIFT["language"]["duplicateuseremail"];
			} else {
				if (!empty($_POST["slaplanid"]))
				{
					updateUserSLAPlan($userid, $_POST["slaplanid"]);
				}

				updateCustomFields(CUSTOMFIELD_USER, $userid);
				printRedirect(sprintf($_SWIFT["language"]["userinsertconfirm"], htmlspecialchars($_POST["email"])), "index.php?_m=core&_a=manageusers&insertuser=".urlencode($_POST["email"]));
				exit;
			}
		}
	}

	$interface->staffHeader($_SWIFT["language"]["users"]." &gt; ".$_SWIFT["language"]["insertuser"], 9);

	$interface->staffNavBar('<a href="index.php?_m=core&_a=manageusers" title="'.$_SWIFT["language"]["users"].'">'.$_SWIFT["language"]["users"].'</a> &raquo; '.'<a href="index.php?_m=core&_a=insertuser" title="'.$_SWIFT["language"]["insertuser"].'">'.$_SWIFT["language"]["insertuser"].'</a>', "", 9);
	
	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderUserForm(INSERT);

	$template->assign("backurl", "index.php?_m=core&_a=manageusers");
	$interface->staffFooter();






/**
* ###############################################
* EDIT USER
* ###############################################
*/
} else if ($eventaction == "edituser") {
	$_user = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."users` WHERE `userid` = '". intval($_REQUEST["userid"]) ."';");
	if (empty($_user["userid"]))
	{
		trigger_error($_SWIFT["language"]["invaliduser"], E_USER_ERROR);
	}
	$_user["emaillist"] = array();
	$dbCore->query("SELECT `email` FROM `". TABLE_PREFIX ."useremails` WHERE `userid` = '". intval($_user["userid"]) ."' ORDER BY `useremailid` ASC;");
	while ($dbCore->nextRecord())
	{
		$_user["emaillist"][] = $dbCore->Record["email"];
	}

	// ======= START USER UPDATE PROCESSING =======
	if ($_POST["step"] == "1")
	{
		if (trim($_POST["fullname"]) == "" || !checkCustomFieldContent(CUSTOMFIELD_USER))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if (trim($_POST["password"]) != "" && $_POST["password"] != $_POST["passwordconfirm"]) {
			$errormessage = $_SWIFT["language"]["passworddontmatch"];
		} else {
			updateUserStaffCP($_user["userid"], $_POST["password"], $_POST["usergroupid"], $_POST["fullname"], iif($_POST["ismanager"]==1, true, false));

			updateCustomFields(CUSTOMFIELD_USER, $_user["userid"]);

			updateUserSLAPlan($_user["userid"], $_POST["slaplanid"]);

			printRedirect(sprintf($_SWIFT["language"]["userupdateconfirm"], htmlspecialchars($_POST["email"])), "index.php?_m=core&_a=manageusers&updateuser=".urlencode($_POST["fullname"]));
			exit;
		}
	}
	$_POST = array_merge($_POST, $_user);
	// ======= END USER UPDATE PROCESSING =======

	// ======= MARK AS STUFF =======
	if ($_GET["markas"] == "validationpending")
	{
		changeUserValidationStatus(array($_user["userid"]), 0);
		$_user["enabled"] = 0;
		$infomessage = sprintf($_SWIFT["language"]["valconfirm"], htmlspecialchars($_user["fullname"]));
	} else if ($_GET["markas"] == "validated") {
		changeUserValidationStatus(array($_user["userid"]), 1);
		$_user["enabled"] = 1;
		$infomessage = sprintf($_SWIFT["language"]["valconfirm"], htmlspecialchars($_user["fullname"]));
	}


	// ======= START GRID RELATED CODE =======
	if ($_GET["do"] == "deleteuseremail" && !empty($_GET["useremailid"]))
	{
		$delresult = deleteUserEmails($_user["userid"], array($_GET["useremailid"]));
		if ($delresult == -1)
		{
			$errormessage = $_SWIFT["language"]["cantdelprimaryemail"];
		} else {
			$infomessage = $_SWIFT["language"]["useremaildelconfirm"];
		}
	} else if ($_POST["do"] == "insertuseremail") {
		if (trim($_POST["email"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
			$displaybox = true;
		} else {
			$insertresult = insertUserEmail($_user["userid"], $_POST["email"]);
			if ($insertresult = false)
			{
				$errormessage = $_SWIFT["language"]["duplicateuseremail"];
				$displaybox = true;
			} else {
				$infomessage = sprintf($_SWIFT["language"]["useremailinsertconfirm"], htmlspecialchars($_POST["email"]));
			}
		}
	} else if ($_GET["do"] == "sendveriemail") {
		$tgroupid = 1;
		foreach ($_SWIFT["tgroupcache"] as $key=>$val)
		{
			if ($val["regusergroupid"] == $_user["usergroupid"])
			{
				$tgroupid = $val["tgroupid"];
				break;
			}
		}

		$template->setGroup($tgroupid);
		$template->loadLanguageSection("misc", TEMPLATE_DB);

		$_email = $dbCore->queryFetch("SELECT `email` FROM `". TABLE_PREFIX ."useremails` WHERE `userid` = '". intval($_user["userid"]) ."' ORDER BY `useremailid` ASC LIMIT 1;");

		if (!empty($_email["email"]) && $_user["enabled"] != 1)
		{
			sendRegistrationUpdateMail(MAIL_VERIFICATION, $_user["userid"], $_user["fullname"], $_email["email"], $_user["userpasswordtxt"], $tgroupid);
			$infomessage = sprintf($_SWIFT["language"]["veriemailconfirm"], htmlspecialchars($_email["email"]));
		} else {
			sendRegistrationUpdateMail(MAIL_SUCCESSREG, $_user["userid"], $_user["fullname"], $_email["email"], $_user["userpasswordtxt"], $tgroupid);
			$infomessage = sprintf($_SWIFT["language"]["uregemailconfirm"], htmlspecialchars($_email["email"]));
		}
	}

	// ======= END GRID RELATED CODE =======

	if (!empty($_GET["updateuseremail"]))
	{
		$infomessage = sprintf($_SWIFT["language"]["useremailupdateconfirm"], htmlspecialchars($_GET["updateuseremail"]));
	}

	$template->assign("user", $_user);
	if ($module->isRegistered(MODULE_TICKETS))
	{
		$template->assign("isedituser", true);
		$template->assign("userid", $_user["userid"]);
		$template->assign("usergroupid", $_user["usergroupid"]);
		$template->assign("cpdepartments", $_SWIFT["departmentcache"]);
		$template->assign("cpdepcount", count($_SWIFT["departmentcache"]));
		$template->assign("cpstatus", $_SWIFT["statuscache"]);
		$template->assign("cpstatuscount", count($_SWIFT["statuscache"]));
	}

	$template->assign("itemoptiontitle", $_SWIFT["language"]["useroptions"]);
	if ($module->isRegistered(MODULE_TICKETS))
	{
		$interface->assignItemOption($_SWIFT["language"]["createticket"], "", "icon_ticket.gif", "tuserticket", '');
		$interface->assignItemOption($_SWIFT["language"]["tusearchticket"], "", "icon_searchlookup.gif", "tusearchticket", '');
	}
	$interface->assignItemOption($_SWIFT["language"]["markas"], "", "icon_check.gif", "tumarkas", '');
	$interface->assignItemOption($_SWIFT["language"]["options"], "", "icon_settings.gif", "tuoptions", '');
	$interface->assignItemOption($_SWIFT["language"]["deleteuser"], "", "icon_delete.gif", "", 'doConfirm(\''. $_SWIFT["language"]["userdelconfirmmsg"] .'\', \'index.php?_m=core&_a=manageusers&do=delete&userid='. $_user["userid"] .'\')');

	$interface->staffHeader($_SWIFT["language"]["users"]." &gt; ".$_SWIFT["language"]["edituser"], 9);

	$interface->staffNavBar('<a href="index.php?_m=core&_a=manageusers" title="'.$_SWIFT["language"]["users"].'">'.$_SWIFT["language"]["users"].'</a> &raquo; '.'<a href="index.php?_m=core&_a=edituser&userid='. intval($_user["userid"]) .'" title="'.$_SWIFT["language"]["edituser"].'">'.$_SWIFT["language"]["edituser"].'</a> &raquo; '.'<a href="index.php?_m=core&_a=edituser&userid='. intval($_user["userid"]) .'" title="'.$_SWIFT["language"]["edituser"].'">'.htmlspecialchars($_user["fullname"]).'</a>', "", 9);

	printInfoBox($infomessage);
	printErrorBox($errormessage);
	// ======= First render the main form =======
	renderUserForm(EDIT);

	// ======= Now render the user email grid =======
	$options["recordsperpage"] = "5";
	$options["sortby"] = "email";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteUserEmails";

	$options["idname"] = "useremailid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["usremail"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'useremails` WHERE `userid` = \''. intval($_user["userid"]) .'\' AND `email` LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_userEmailFields";
	$options["appendurl"] = "&userid=".$_user["userid"];

	$options["toolbar"][0]["title"] = $_SWIFT["language"]["insertnewuseremail"];
	$options["toolbar"][0]["url"] = "javascript:switchDisplay('insertuseremail');";

	$fields[0]["name"] = "email";
	$fields[0]["title"] = $_SWIFT["language"]["usremail"];
	$fields[0]["width"] = "";

	$fields[1]["type"] = "custom";
	$fields[1]["name"] = "options";
	$fields[1]["title"] = $_SWIFT["language"]["options"];
	$fields[1]["width"] = "160";
	$fields[1]["align"] = "center";

	// ======= START INSERT EMAIL DIV =======
	echo "<BR />";
	echo '<div id="insertuseremail" style="DISPLAY:'. iif($displaybox, "block", "none") .';">'.SWIFT_CRLF;
	printFormStart();
	printMainTableHeader($_SWIFT["language"]["insertnewuseremail"]);

	printTextRow("email", $_SWIFT["language"]["usremail"], $_SWIFT["language"]["desc_usremail"], "text", $_POST["email"]);

	printSubmitRow($_SWIFT["language"]["insert"]);

	printMainTableFooter();
	addHiddenField("_m", "core");
	addHiddenField("_a", "edituser");
	addHiddenField("userid", $_user["userid"]);
	addHiddenField("do", "insertuseremail");
	printFormEnd();
	echo '<BR /></div>'.SWIFT_CRLF;
	// ======= END INSERT EMAIL DIV =======


	$grid = new Grid();

	$_selectquery = 'SELECT * FROM `'. TABLE_PREFIX .'useremails` WHERE `userid` = \''. intval($_user["userid"]) .'\' $_sortjoin;';
	$_countquery = 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'useremails` WHERE `userid` = \''. intval($_user["userid"]) .'\';';
	$_searchquery = 'SELECT * FROM `'. TABLE_PREFIX .'useremails` WHERE `userid` = \''. intval($_user["userid"]) .'\' AND `email` LIKE \'%$_searchstr%\' $_sortjoin;';
	
	addHiddenField("userid", $_user["userid"]);
	$grid->start("useremails", $_SWIFT["language"]["useremaillist"], $_selectquery, $_countquery, $_searchquery, $fields, $options);
	printInfoBox($gridinfomessage);
	printErrorBox($griderrormessage);

	$grid->display("useremails");
	// ======= END GRID =======

	$template->assign("backurl", "index.php?_m=core&_a=manageusers");
	$interface->staffFooter();






/**
* ###############################################
* EDIT USER EMAIL
* ###############################################
*/
} else if ($eventaction == "edituseremail") {
	$_useremail = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."useremails` WHERE `useremailid` = '". intval($_REQUEST["useremailid"]) ."';");
	if (empty($_useremail["useremailid"]))
	{
		trigger_error($_SWIFT["language"]["invaliduseremail"], E_USER_ERROR);
	}

	// ======= START USER EMAIL UPDATE PROCESSING =======
	if ($_POST["step"] == "1")
	{
		if (trim($_POST["email"]) == "")
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} 
		else if($_useremail["email"] != $_POST["email"])
		{
			$updateresult = updateUserEmail($_useremail["userid"], $_useremail["useremailid"], $_POST["email"]);

			if (!$updateresult)
			{
				$errormessage = $_SWIFT["language"]["duplicateuseremail"];
			} else {
				$_ticketidlist = $_ticketpostidlist = array();
				$dbCore->query("SELECT `ticketid` FROM `". TABLE_PREFIX ."tickets` WHERE `email` = '". $dbCore->escape($_useremail["email"]) ."';");
				while ($dbCore->nextRecord())
				{
					$_ticketidlist[] = $dbCore->Record["ticketid"];
				}

				$dbCore->query("SELECT `ticketpostid` FROM `". TABLE_PREFIX ."ticketposts` WHERE `email` = '". $dbCore->escape($_useremail["email"]) ."';");
				while ($dbCore->nextRecord())
				{
					$_ticketpostidlist[] = $dbCore->Record["ticketpostid"];
				}
				
				if (!empty($_ticketidlist))
				{
					$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `email` = '". $dbCore->escape($_POST["email"]) ."' WHERE `ticketid` IN (". buildIN($_ticketidlist) .");");
				}
				
				if (!empty($_ticketpostidlist))
				{
					$dbCore->query("UPDATE `". TABLE_PREFIX ."ticketposts` SET `email` = '". $dbCore->escape($_POST["email"]) ."' WHERE `ticketpostid` IN (". buildIN($_ticketpostidlist) .");");
				}
					printRedirect(sprintf($_SWIFT["language"]["useremailupdateconfirm"], htmlspecialchars($_POST["email"])), "index.php?_m=core&_a=edituser&userid=". intval($_useremail["userid"]) ."&updateuseremail=".urlencode($_POST["email"]));
					exit;
				}
		}else {
			printRedirect(sprintf($_SWIFT["language"]["useremailupdateconfirm"], htmlspecialchars($_POST["email"])), "index.php?_m=core&_a=edituser&userid=". intval($_useremail["userid"]) ."&updateuseremail=".urlencode($_POST["email"]));
			exit;
		}
	}
	// ======= END USER EMAIL UPDATE PROCESSING =======

	$interface->staffHeader($_SWIFT["language"]["users"]." &gt; ".$_SWIFT["language"]["edituseremail"], 9);

	$interface->staffNavBar('<a href="index.php?_m=core&_a=manageusers" title="'.$_SWIFT["language"]["users"].'">'.$_SWIFT["language"]["users"].'</a> &raquo; <a href="index.php?_m=core&_a=edituser&userid='. intval($_useremail["userid"]) .'" title="'.$_SWIFT["language"]["edituser"].'">'.$_SWIFT["language"]["edituser"].'</a> &raquo; <a href="index.php?_m=core&_a=edituseremail&useremailid='. intval($_useremail["useremailid"]) .'" title="'.$_SWIFT["language"]["edituseremail"].'">'.$_SWIFT["language"]["edituseremail"].'</a>', "", 9);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["edituseremail"]);

	printTextRow("email", $_SWIFT["language"]["usremail"], $_SWIFT["language"]["desc_usremail"], "text", $_useremail["email"]);

	printSubmitRow($_SWIFT["language"]["update"]);

	printMainTableFooter();
	addHiddenField("_m", "core");
	addHiddenField("_a", "edituseremail");
	addHiddenField("useremailid", $_useremail["useremailid"]);
	addHiddenField("step", "1");
	printFormEnd();

	$template->assign("backurl", "index.php?_m=core&_a=edituser&userid=".intval($_useremail["userid"]));
	$interface->staffFooter();







}

?>